package classificationlogic

import (
	"common/dao/model"
	"common/utils"
	"context"
	"errors"
	"github.com/jinzhu/copier"
	"gorm.io/gorm"
	"time"

	"service/internal/svc"
	"service/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateLogic) Create(in *pb.SysClassificationResp) (*pb.Emp, error) {
	// todo: add your logic here and delete this line
	if in.Name == "" {
		return nil, errors.New("name is null")
	}
	db := l.svcCtx.DB.Table(model.TableNameClassification)
	err := db.Transaction(func(tx *gorm.DB) error {
		var (
			data = model.Classification{}
		)
		err := copier.CopyWithOption(&data, in, copier.Option{IgnoreEmpty: true})
		if err != nil {
			return err
		}
		data.UUID = utils.GetUuid()
		t := time.Now()
		data.CreateTime = &t
		data.DeleTime = nil
		if err := tx.Create(&data).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &pb.Emp{}, nil
}
